package http

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"probeping/src/model"
	"probeping/src/store"
	"strconv"
	"time"
)

func configApiRoutes() {

	//配置文件API
	http.HandleFunc("/api/config.json", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		nconf := model.Config{}
		cfgJson, _ := json.Marshal(store.Cfg)
		json.Unmarshal(cfgJson, &nconf)
		onconf, _ := json.Marshal(nconf)
		var out bytes.Buffer
		json.Indent(&out, onconf, "", "\t")
		o := out.String()
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintln(w, o)
	})

	//主机列表API
	http.HandleFunc("/api/host.json", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		jsonBuf, _ := json.Marshal(store.Host)
		var out bytes.Buffer
		json.Indent(&out, jsonBuf, "", "\t")
		o := out.String()
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintln(w, o)
	})

	//Ping历史
	http.HandleFunc("/api/ping.json", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()

		log.Println(r.Form)
		if len(r.Form["ip"]) == 0 || r.Form["ip"][0] == "" {
			o := "请输入IP地址 !"
			http.Error(w, o, http.StatusBadRequest)
			return
		}

		var tableip string
		var timeStart int64
		var timeEnd int64
		var timeStartStr string
		var timeEndStr string
		tableip = r.Form["ip"][0]
		if len(r.Form["startTime"]) > 0 && len(r.Form["endTime"]) > 0 {
			timeStartStr = r.Form["startTime"][0]
			if timeStartStr != "" {
				tms, _ := time.Parse("2006-01-02 15:04", timeStartStr)
				timeStart = tms.Unix() - 8*60*60
			} else {
				timeStart = time.Now().Unix() - 2*60*60
				timeStartStr = time.Unix(timeStart, 0).Format("2006-01-02 15:04")
			}
			timeEndStr = r.Form["endTime"][0]
			if timeEndStr != "" {
				tmn, _ := time.Parse("2006-01-02 15:04", timeEndStr)
				timeEnd = tmn.Unix() - 8*60*60
			} else {
				timeEnd = time.Now().Unix()
				timeEndStr = time.Unix(timeEnd, 0).Format("2006-01-02 15:04")
			}
		} else {
			timeStart = time.Now().Unix() - 2*60*60
			timeStartStr = time.Unix(timeStart, 0).Format("2006-01-02 15:04")
			timeEnd = time.Now().Unix()
			timeEndStr = time.Unix(timeEnd, 0).Format("2006-01-02 15:04")
		}

		var page int
		if len(r.Form["page"]) > 0 {
			page, _ = strconv.Atoi(r.Form["page"][0])
		}
		if page == 0 {
			page = 1
		}

		offset := page * 10

		pingLogs := []model.PingLog{}
		querySql := "SELECT target,logtime,maxdelay,mindelay,avgdelay,losspk FROM `pinglog` where target='" + tableip + "' and logtime between '" + timeStartStr + "' and '" + timeEndStr + "' order by logtime LIMIT 10 OFFSET " + strconv.Itoa(offset)
		rows, err := store.Db.Query(querySql)
		log.Println("[func:/api/ping.json] Query ", querySql)
		if err != nil {
			log.Println("[func:/api/ping.json] Query ", err)
		} else {
			for rows.Next() {
				var pingLog model.PingLog
				err := rows.Scan(&pingLog.Target, &pingLog.LogTime, &pingLog.MaxDelay, &pingLog.MinDelay, &pingLog.AvgDelay, &pingLog.LossPk)
				if err != nil {
					log.Println("[/api/ping.json] Rows", err)
					continue
				}
				pingLogs = append(pingLogs, pingLog)
			}
			rows.Close()
		}

		jsonBuf, _ := json.Marshal(pingLogs)
		var out bytes.Buffer
		json.Indent(&out, jsonBuf, "", "\t")
		o := out.String()
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintln(w, o)
	})

}
